class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        if not head:
            return head
        if not head.next:
            return head
        if head.val >= x:
            big_node = head
        else:
            left = head
            right = head.next
            while right:
                if right.val < x:
                    left = right
                    right = right.next
                else:
                    big_node = left
                    break
        left = head
        right = head.next
        if left.val >= x:
            flag = True
        else:
            flag = False
        while right:
            if right.val < x:
                if flag:
                    if big_node == head and head.val >= x:
                        left.next = right.next
                        right.next = head
                        head = right
                        big_node = head
                    else:
                        left.next = right.next
                        right.next = big_node.next
                        big_node.next = right
                        big_node = right
                    right = right.next
                else:
                    left = right
                    right = right.next
        return head